<?php

namespace app\common\service\setting;
use app\common\cache\setting\SettingPriceRangeCache;
use app\common\model\setting\SettingPriceAttributesModel;
use app\common\model\setting\SettingPriceConditionModel;
use app\common\model\setting\SettingPriceRangeModel;
use app\common\service\file\FileService;
use think\facade\Db;

/**
 * 价格区间
 */
class SettingPriceRangeService
{
    /**
     * 添加、修改字段
     * @var array
     */
    public static $edit_field = [
        'id/d'=>null,//主键id
        'code/s'=>null,//编码
        'store_platform_id/d'=>null,//店铺类型
        'merchant_fees/f'=>0,//商家收费
        'user_consumption/f'=>0,//用户消耗
        'price_start/f'=>0,//价格起
        'price_close/f'=>0,//价格止
        'increment_description/s'=>null,//增值描述
        'increment_type/s'=>null,//增值类型
        'comment_type/s'=>null,//评价类型
        'comment_describe/s'=>null,//评价描述
        'is_disable/d'=>0,//是否禁用，1是0否
        'is_delete/d'=>0,//是否删除，1是0否
        'sort/d'=>250,//排序
        'status/d'=>null,//0:佣金价格 1:增值价格 2:评论价格 3:追评价格
        'mer_describe/s'=>null,//商家端描述
        'mer_explain/s'=>null,//商家端说明
        'mer_image_id/d'=>null,//商家端示例图
        'user_describe/s'=>null,//用户端描述
        'user_image_id/d'=>null,//用户端示例图
        'user_help_code/s'=>null,//用户帮助编码
        'platform_ids'=>null,//店铺平台
        'product_type_ids'=>null,//活动分类
    ];

    //查询条件
    public static function getCondition($id)
    {
        $model = new SettingPriceConditionModel();
        $info = $model->where('setting_price_range_id',$id)->select()->toArray();
        $data = [
            'setting_price_range_id'=>$id,
            'type'=>0,//类型：0、单选  1、多选  3、文本框 4、时间控件
            'radio_value'=>null,//默认值
            'check_value'=>[],
            'region_value'=>[],
            'values'=>[],
        ];
        foreach ($info as $key => $item) {
            if($item['type'] == 0 && $item['is_default'] == 1){
                $data['radio_value'] = $item['value'];
            }
            if($item['type'] == 1 && $item['is_default'] == 1){
                array_push($data['check_value'],$item['value']);
            }
            if($item['type'] == 4){
                if($item['is_default'] == 1){
                    array_push($data['region_value'],$item['value']);
                }
                $item['label'] = intval($item['label']);
            }
            if($item['type'] == 3 && $item['value']){
                $item['value'] = explode(",",$item['value']);
            }
            array_push($data['values'],$item);
        }
        return $data;
    }
    /**
     * 保存条件
     * @param $param
     * @return void
     */
    public static function saveCondition($setting_price_range_id,$param)
    {
        $model = new SettingPriceConditionModel();
        $values = $param['values'];
        $data = array();
        $radio_index= 0;
        $check_index= 0;
        $region_index= 0;
        foreach ($values as $key => $item) {
            $is_default=0;//判断是否选中
            $value = null;//值

            switch (intval($item['type'])) {
                case 0://单选
                        if($param['radio_value'] == $radio_index){
                            $is_default=true;
                        }
                        $value = $radio_index;
                        $radio_index+=1;
                    break;
                case 1://多选
                    if(in_array($check_index, $param['check_value'])){
                        $is_default=true;
                    }
                    $value = $check_index;
                    $check_index+=1;
                    break;
                case 3://时间区间
                    if($item['value'] && count($item['value'])>0){
                        $value = implode(',',$item['value']);
                    }
                    break;
                case 4://地区
                    if(in_array($region_index, $param['region_value'])){
                        $is_default=true;
                    }
                    $value = $region_index;
                    $region_index+=1;
                    break;
                default:
                    $value =$item['value'];
                    break;
            }
            array_push($data,[
                'setting_price_range_id'=>$setting_price_range_id,
                'type'=>$item['type'],
                'label'=>$item['label'],
                'value'=>$value,
                'is_default'=>$is_default,
            ]);
        }
        $model->startTrans();
        try {
            $model->where('setting_price_range_id',$setting_price_range_id)->delete();
            if(count($data)>0){
                $model->saveAll($data);
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }
        if (isset($errmsg)) {
            exception($errmsg);
        }
        return true;
    }

    /**
     * 价格区间列表
     *
     * @param array  $where 条件
     * @param int    $page  页数
     * @param int    $limit 数量
     * @param array  $order 排序
     * @param string $field 字段
     *
     * @return array
     */
    public static function list($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $sql = self::getListSql($where,$order);
        if ($page == 0 || $limit == 0) {
            return Db::query($sql);
        }
        $count =  Db::query("select count(*) as count from (".$sql.") as a");
        $count=$count[0]['count'];
        $pages = ceil($count / $limit);
        // 计算偏移量
        $offset = ($page - 1) * $limit;
        $list = Db::query($sql. " LIMIT $offset, $limit");
        //查询图片路径
        foreach ($list as &$item) {
            if($item['mer_image_id']){
                $file = FileService::info($item['mer_image_id']);
                if($file && isset($file['file_url'])){
                    $item['mer_image_url'] =$file['file_url'];
                }
            }
            if($item['user_image_id']){
                $file = FileService::info($item['user_image_id']);
                if($file && isset($file['file_url'])){
                    $item['user_image_url'] =$file['file_url'];
                }
            }
        }
        return compact('count', 'pages', 'page', 'limit', 'list');
    }

    private static function getListSql($where = [], $order = [])
    {
        $status = 0;//根据类型排序
        //组装条件
        $where_sql = "";
        foreach ($where as $key=>$val){
            if($where_sql!=""){
                $where_sql .=" and ";
            }
            if($val[0] == 'platform_ids' && isset($val[2])){
                $where_sql .="FIND_IN_SET(".$val[2].",a.platform_ids)> 0";
            }else if($val[0] == 'product_type_ids' && isset($val[2])) {
                $where_sql .="FIND_IN_SET(".$val[2].",a.product_type_ids)> 0";
            }else if(is_array($val[2])){
                $where_sql .="r.".$val[0]." ".$val[1]."(".implode(',',$val[2]).")";
            }else{
                $where_sql .="r.".$val[0]." ".$val[1]." '".$val[2]."' ";
            }
            if($val[0] == 'status'){
                if(is_array($val[2]) && count($val[2])>0){
                    $status =$val[2][0];
                }else{
                    $status =$val[2];
                }
            }
        }
        //组装排序
        $order_sql = "";
        foreach ($order as $key=>$val){
            if($order_sql!=""){
                $order_sql .=" , ";
            }
            $order_sql .="r.".$key." ".$val." ";
        }
        if($order_sql == ""){
            if($status == 0) {
                $order_sql = "r.code ASC,r.sort asc,r.id desc";
            }else{
                $order_sql = "r.sort asc,a.product_type_ids asc,a.platform_ids asc,r.id desc";
            }
        }
        $sql = <<<SQL
            SELECT 
                r.*,
                a.platform_ids,
                a.product_type_ids,
                a.platform_names,
                a.product_type_names
            FROM 
                ya_setting_price_range r
            LEFT JOIN (
                  SELECT
                    `setting_price_range_id`,
                    GROUP_CONCAT( setting_store_platform_id ) AS platform_ids,
                    GROUP_CONCAT( shop_product_type_id ) AS product_type_ids,
                    GROUP_CONCAT( s.title ) AS platform_names,
                    GROUP_CONCAT( p.title ) AS product_type_names
                  FROM
                    `ya_setting_price_attributes` as attr
                   LEFT JOIN ya_setting_store_platform s ON attr.setting_store_platform_id = s.id
                   LEFT JOIN ya_shop_product_type p ON attr.shop_product_type_id = p.id   
                  GROUP BY
                    `setting_price_range_id` 
            ) a ON r.id = a.setting_price_range_id
            WHERE
                {$where_sql}
            GROUP BY 
                r.id
            ORDER BY 
                {$order_sql}
        SQL;
       return $sql;
    }


    /**
     * 查询价格区间（发布商品使用）
     * @param $where
     * @param $page
     * @param $limit
     * @param $order
     * @param $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getPriceRange($where = [], $order = [])
    {
        $sql = self::getListSql($where,$order);
        $list = Db::query($sql);
        return self::conditionMachining($list);
    }

    //条件格式化
    private static function conditionMachining($result)
    {
        $f_increment_values = [];//条件值
        // 遍历查询结果
        foreach ($result as &$item) {
            //字符串转数组
            if($item['platform_ids']){
                $item['platform_ids'] =  array_map('intval',explode(',',$item['platform_ids']));
            }
            if($item['product_type_ids']){
                $item['product_type_ids'] =  array_map('intval',explode(',',$item['product_type_ids']));
            }
            if($item['platform_names']){
                $item['platform_names'] =  explode(',',$item['platform_names']);
            }
            if($item['product_type_names']){
                $item['product_type_names'] =  explode(',',$item['product_type_names']);
            }
            //图片处理
            if($item['mer_image_id']){
                $file = FileService::info($item['mer_image_id']);
                if($file && isset($file['file_url'])){
                    $item['mer_image_url'] =$file['file_url'];
                }
            }
            if($item['user_image_id']){
                $file = FileService::info($item['user_image_id']);
                if($file && isset($file['file_url'])){
                    $item['user_image_url'] =$file['file_url'];
                }
            }
            // 检查增值佣金是否有 condition
            if ($item['status'] == 1) {
                $f_increment_values['price_range_'.$item['id']] = null;//订单数量
                $f_increment_values['price_range_'.$item['id'].'_0'] = null;//单选框选择值
                $f_increment_values['price_range_'.$item['id'].'_1'] = [];
                $f_increment_values['price_range_'.$item['id'].'_2'] = null;
                $f_increment_values['price_range_'.$item['id'].'_3'] = [];
                $f_increment_values['price_range_'.$item['id'].'_4'] = [];
                // 定义一个数组来存储分组结果
                $groupedResult = [];
                $item['condition'] = SettingPriceConditionModel::where('setting_price_range_id',$item['id'])->select()->toArray();
                foreach ($item['condition'] as $condition) {
                    // 获取 type 值
                    $type = $condition['type'];
                    //获取默认值
                    switch (intval($type)) {
                        case 0://单选
                            if($condition['is_default'] == 1){
                                $f_increment_values['price_range_'.$item['id'].'_'.$type] = $condition['value'];
                            }
                            break;
                        case 1://多选
                            if($condition['is_default'] == 1) {
                                array_push($f_increment_values['price_range_' . $item['id'].'_'.$type], $condition['value']);
                            }
                            break;
                        case 3://时间区间
                            if($condition['value']) {
                                $f_increment_values['price_range_' . $item['id'].'_'.$type] = explode(",",$condition['value']);
                            }
                            break;
                        case 4://地区
                            if($condition['is_default'] == 1) {
                                array_push($f_increment_values['price_range_' . $item['id'].'_'.$type],intval($condition['value']));
                            }
                            //根据id查询地区名称
                            $region = RegionService::info(intval($condition['label']));
                            $condition['label'] = isset($region['region_fullname']) ?$region['region_fullname']:"未知地区";
                            break;
                        default:
                            $f_increment_values['price_range_' . $item['id'].'_'.$type] =$condition['value'];
                            break;
                    }
                    // 根据 type 分组
                    if (!isset($groupedResult[$type])) {
                        $groupedResult[$type] = [];
                    }
                    // 将 condition 添加到相应的 type 分组中
                    $groupedResult[$type][] = $condition;
                }
                $item['condition'] =$groupedResult;
            }
        }
        return compact('result', 'f_increment_values');
    }

    //查询评论类型
    public static function getCommentTypes(){
        return SettingPriceRangeModel::COMMENT_TYPES;
    }
    /**
     * 价格区间信息
     *
     * @param int  $id   价格区间id
     * @param bool $exce 不存在是否抛出异常
     *
     * @return array|Exception
     */
    public static function info($id, $exce = true)
    {
        $info = SettingPriceRangeCache::get($id);
        if (empty($info)) {
            $model = new SettingPriceRangeModel();
            $with     = ['platforms','productTypes','merImage','userImage'];
            $append   = ['platform_names','product_type_names','mer_image_url','user_image_url','platform_ids','product_type_ids'];
            $hidden   = ['platforms','productTypes','merImage','userImage'];
            $info = $model->with($with)->find($id);
            if (empty($info)) {
                if ($exce) {
                    exception('数据不存在：' . $id);
                }
                return [];
            }
            $info = $info->append($append)->hidden($hidden)->toArray();
            SettingPriceRangeCache::set($id, $info);
        }
        return $info;
    }
    /**
     * 价格区间添加
     *
     * @param array $param 价格区间信息
     *
     * @return array|Exception
     */
    public static function add($param)
    {
        $model = new SettingPriceRangeModel();
        $pk = $model->getPk();

        unset($param[$pk]);

        $param['create_uid']  = user_id();
        $param['create_time'] = datetime();

        // 启动事务
        $model->startTrans();
        try {
            // 添加
            $model->save($param);
            // 添加店铺平台
            if (isset($param['platform_ids'])) {
                $model->platforms()->saveAll($param['platform_ids']);
            }
            // 添加活动分类
            if (isset($param['product_type_ids'])) {
                $model->productTypes()->saveAll($param['product_type_ids']);
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        $param[$pk] = $model->$pk;

        return $param;
    }

    //批量新增商品基础佣金
    public static function batchAdd($data,$platform_ids=[],$product_type_ids=[])
    {
        $model = new SettingPriceRangeModel();
        $pk = $model->getPk();

        // 启动事务
        $model->startTrans();
        try {
            // 添加
            $res = $model->saveAll($data);
            foreach ($res as $param) {
                //效验
                $checkRes = self::checkPriceStartExisted($param->toArray(),$platform_ids,$product_type_ids);
                if($checkRes!==true){
                    exception($checkRes);
                }
                // 添加店铺平台
                if (count($platform_ids)>0) {
                    $param->platforms()->saveAll($platform_ids);
                }
                // 添加活动分类
                if (count($product_type_ids)>0) {
                    $param->productTypes()->saveAll($product_type_ids);
                }
                $param->code = "BATCH".$param[$pk];
                $param->save();
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }


        return true;
    }
    //验证重复
    protected static function checkPriceStartExisted($data, $platform_ids=[],$product_type_ids=[])
    {
        // 获取符合 platform_ids 条件的 setting_price_range_id
        $platform_range_ids = SettingPriceAttributesModel::alias('a')
            ->leftJoin('setting_price_range','setting_price_range.id = a.setting_price_range_id')
            ->whereIn('setting_price_range.is_delete', 0)
            ->whereIn('a.setting_store_platform_id', $platform_ids)
            ->group('a.setting_price_range_id')
            ->field('a.setting_price_range_id')
            ->select()
            ->toArray();
        $platform_range_ids = array_column($platform_range_ids, 'setting_price_range_id');

        // 获取符合 product_type_ids 条件的 setting_price_range_id
        $product_type_range_ids = SettingPriceAttributesModel::alias('a')
            ->leftJoin('setting_price_range','setting_price_range.id = a.setting_price_range_id')
            ->whereIn('setting_price_range.is_delete', 0)
            ->whereIn('a.shop_product_type_id', $product_type_ids)
            ->group('a.setting_price_range_id')
            ->field('a.setting_price_range_id')
            ->select()
            ->toArray();
        $product_type_range_ids = array_column($product_type_range_ids, 'setting_price_range_id');

        // 取交集
        $setting_price_range_ids = array_intersect($platform_range_ids, $product_type_range_ids);

        $model = new SettingPriceRangeModel();
        $pk = $model->getPk();
        $id = $data[$pk] ?? 0;
        $where[] = [$pk, '<>', $id];
        $where[] = ['status', '=', $data['status']];
        if(count($setting_price_range_ids)>0){
            $where[] = [$pk, 'in', $setting_price_range_ids];
            $where[] = ['price_start', '>=', $data['price_start']];
            $where[] = ['price_close', '<=', $data['price_close']];
        }else{
            $where[] = [$pk, 'in', [0]];
        }
        $where = where_delete($where);
        $info = $model->field($pk)->where($where)->find();
        if ($info) {
            return '价格区间已存在：' . $data['price_start'].'至'.$data['price_close'];
        }
        return true;
    }
     /**
     * 价格区间修改
     *
     * @param int|array $ids   价格区间id
     * @param array     $param 价格区间信息
     *
     * @return array|Exception
     */
    public static function edit($ids, $param = [])
    {
        $model = new SettingPriceRangeModel();
        $pk = $model->getPk();

        unset($param[$pk], $param['ids']);

        $param['update_uid']  = user_id();
        $param['update_time'] = datetime();

        // 启动事务
        $model->startTrans();
        try {
            if (is_numeric($ids)) {
                $ids = [$ids];
            }
            // 修改
            $model->where($pk, 'in', $ids)->update($param);
            if (var_isset($param, ['platform_ids'])) {
                foreach ($ids as $id) {
                    $info = $model->find($id);
                    // 修改店铺平台
                    if (isset($param['platform_ids'])) {
                        $info = $info->append(['platform_ids']);
                        relation_update($info, $info['platform_ids'], $param['platform_ids'], 'platforms');
                    }
                    // 修改活动分类
                    if (isset($param['product_type_ids'])) {
                        $info = $info->append(['product_type_ids']);
                        relation_update($info, $info['product_type_ids'], $param['product_type_ids'], 'productTypes');
                    }
                }
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        $param['ids'] = $ids;

//        SettingPriceRangeCache::del($ids);
        SettingPriceRangeCache::clear();

        return $param;
    }

    /**
     * 价格区间删除
     *
     * @param array $ids  价格区间id
     * @param bool  $real 是否真实删除
     *
     * @return array|Exception
     */
    public static function dele($ids, $real = false)
    {
        $model = new SettingPriceRangeModel();
        $pk = $model->getPk();

        // 启动事务
        $model->startTrans();
        try {
            if (is_numeric($ids)) {
                $ids = [$ids];
            }
            if ($real) {
                foreach ($ids as $id) {
                    $info = $model->find($id);
                    // 删除平台
                    $info->platforms()->detach();
                    // 删除活动分类
                    $info->productTypes()->detach();
                }
                $model->where($pk, 'in', $ids)->delete();
            } else {
                $update = delete_update();
                $model->where($pk, 'in', $ids)->update($update);
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        $update['ids'] = $ids;
//        SettingPriceRangeCache::del($ids);
        SettingPriceRangeCache::clear();
        return $update;
    }

    /**
     * 根据价格区间编码查询条件值
     * @Author: 易军辉
     * @DateTime:2024-08-06 12:12
     * @param $code
     */
    public static function getConditionByCode($code='')
    {
        $list = SettingPriceRangeCache::get($code);
        if (empty($list)) {
            $model = new SettingPriceConditionModel();
            $list = $model->leftJoin('ya_setting_price_range','ya_setting_price_range.id = ya_setting_price_condition.setting_price_range_id')
                ->where('ya_setting_price_range.code',$code)
                ->field('value,label')
                ->select()
                ->toArray();
            foreach ($list as $key=>$val){
                $list[$key]['value'] = (int)$val['value'];
            }
            SettingPriceRangeCache::set($code, $list);
        }
        return $list;
    }

    /**
     * 获取年龄段
     * @Author: 易军辉
     * @DateTime:2024-08-07 17:04
     */
    public static function getAgeList()
    {
        $age_list = SettingPriceRangeService::getConditionByCode(SettingPriceRangeModel::INCREMENT_AGE_CODE);
        if(!$age_list){
            $age_list =array(
                ['value'=>0,'label'=>'18-25'],
                ['value'=>1,'label'=>'26-35'],
                ['value'=>2,'label'=>'36-49'],
                ['value'=>3,'label'=>'50以上'],
            );
        }
        return $age_list;
    }
}
